/**
 * 
 */
package org.agiba.jira.plugin.xwiki;

import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.agiba.jira.plugin.model.XWikiDocumentInfo;
import org.agiba.jira.plugin.model.XWikiInstance;
import org.agiba.jira.plugin.model.XWikiSpaceInfo;
import org.agiba.jira.plugin.persistence.ConfigurationHandler;
import org.apache.commons.lang.StringUtils;
import org.apache.xmlrpc.XmlRpcException;
import org.codehaus.swizzle.confluence.SearchResult;
import org.codehaus.swizzle.confluence.SpaceSummary;
import org.xwiki.xmlrpc.XWikiXmlRpcClient;
import org.xwiki.xmlrpc.model.XWikiPageSummary;

/**
 * @author kamann
 * 
 */
public class XWikiRPCService {
	private static ConfigurationHandler handler = new ConfigurationHandler(999901l, "xwiki", "1.0");
	
	public List<XWikiInstance> findAllXwikiInstances(){
		List<String> keys = handler.loadInstanceKeys();
		List<XWikiInstance> instances = new ArrayList<XWikiInstance>();
		
		for (String key : keys) {
			XWikiInstance instance = handler.loadXWikiInstance(key);
			instance.setKey(key);
			instances.add(instance);
		}
		return instances;
	}
	
	public XWikiInstance findXWikiInstanceByKey(String key) {
		return handler.loadXWikiInstance(key);
	}

	public void saveXWikiInstance(XWikiInstance instance){
		handler.saveXWikiInstance(instance);
	}
	
	public void removeXWikiInstance(XWikiInstance instance){
		handler.removeInstance(instance);
	}
	
	public List<XWikiDocumentInfo> findAllDocuments(XWikiInstance xwikiInstance) {
		List<XWikiDocumentInfo> documents = new ArrayList<XWikiDocumentInfo>();
		XWikiXmlRpcClient client;

		client = new XWikiRPCConnection(xwikiInstance).connectAndLogin();
		List<XWikiPageSummary> result;
		try {
			result = client.getPages("Main");

			for (XWikiPageSummary rs : result) {
				documents.add(new XWikiDocumentInfo().withName(rs.getId())
						.withTitle(rs.getTitle()).withUrl(rs.getUrl()));
			}
		} catch (XmlRpcException e) {
			e.printStackTrace();
		}
		return documents;
	}
	
	public List<XWikiDocumentInfo> findDocumentsByQuery(
			XWikiInstance xwikiInstance, String spaceName, String query) {
		List<XWikiDocumentInfo> documents = new ArrayList<XWikiDocumentInfo>();
		XWikiXmlRpcClient client;

		client = new XWikiRPCConnection(xwikiInstance).connectAndLogin();
		List<SearchResult> result;
		try {
			result = client.search(query, 25);
			
			if (result.size() > 0){
				for (SearchResult searchResult : result) {
					String id = searchResult.getId();
					String[] keys = id.split("\\.");
					String space = id;
					String page = id;
					String url = "";
					
					if (keys.length == 2){
						space = keys[0];
						page = keys[1];
					}


					boolean isInSearchScope = false;
					if (StringUtils.isNotEmpty(spaceName)) {
						isInSearchScope = space.equals(spaceName);
					} else {
						isInSearchScope = xwikiInstance.getSpacesAsStringList()
								.contains(space);
					}

					if (isInSearchScope) {
						url = xwikiInstance.getUrl()+"/bin/view/"+space+"/"+page;
						
						documents.add(new XWikiDocumentInfo()
						.withTitle(page)
						.withName(searchResult.getId())
						.withUrl(url));
					}
					
					
					
					
					
				}
			}

			
		} catch (XmlRpcException e) {
			e.printStackTrace();
		}
		return documents;
	}

	public List<XWikiSpaceInfo> findAllSpaces(XWikiInstance xwikiInstance){
		List<XWikiSpaceInfo> spaces = new ArrayList<XWikiSpaceInfo>();
		XWikiXmlRpcClient client;

		client = new XWikiRPCConnection(xwikiInstance).connectAndLogin();
		if (client == null) {
			return spaces;
		}
		List<SpaceSummary> result;
		
		try {
			result = client.getSpaces();
			for (SpaceSummary spaceSummary : result) {
				spaces.add(new XWikiSpaceInfo().withKey(spaceSummary.getKey()));
			}
		} catch (XmlRpcException e) {
			e.printStackTrace();
		}
		return spaces;
	}

	private class XWikiRPCConnection {
		private XWikiInstance xwikiInstance;

		public XWikiRPCConnection(XWikiInstance xwikiInstance) {
			this.xwikiInstance = xwikiInstance;
		}

		public XWikiXmlRpcClient connectAndLogin() {
			XWikiXmlRpcClient rpc = null;
			String url = xwikiInstance.getUrl();
			
			if (!url.endsWith("/xwiki/xmlrpc/confluence")) {
				url += "/xmlrpc/confluence";
			}
			
			if (StringUtils.isEmpty(xwikiInstance.getCredentials().getUid())
					|| StringUtils.isEmpty(xwikiInstance.getCredentials()
							.getPwd())) {
				return rpc;
			}

			try {
				rpc = new XWikiXmlRpcClient(url);
				rpc.login(xwikiInstance.getCredentials().getUid(),
						xwikiInstance.getCredentials().getPwd());
			} catch (XmlRpcException e) {
				e.printStackTrace();
				rpc = null;
			} catch (MalformedURLException e) {
				e.printStackTrace();
				rpc = null;
			}

			return rpc;
		}

	}
}
